<?php

namespace library;

use GuzzleHttp\Client;
use support\Redis;

class wechat
{


    //获取微信小程序的openid
    public function get_openid($js_code)
    {
        $appid = env('WECHAT_APPID', '');
        $secret = env('WECHAT_SECRET', '');
        //改成
        //创建一个有基本URI的客户端
        $client = new Client();
        //发送请求
        $response = $client->request('GET', 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $js_code . '&grant_type=authorization_code');
        //获取返回数据
        $data = json_decode($response->getBody(), true);
        if (isset($data['openid'])) {
            return [$data['openid'], $data['unionid']];
        }
        return [null, null];
    }


    //获取Access token
    public static function get_access_token()
    {
        if ($access_token = Redis::get('zh_wechat_access_token')) {
            return $access_token;
        }

        $client = new Client();
        $url = 'https://api.weixin.qq.com/cgi-bin/token?appid=' . env('WECHAT_APPID') . '&secret=' . env('WECHAT_SECRET') . '&grant_type=client_credential';
        $res = $client->request('GET', $url);
        $data = json_decode($res->getBody(), true);
        if (isset($data['access_token'])) {
            Redis::set('zh_wechat_access_token', $data['access_token'], 'EX', 7000);
        }
        return $data['access_token'] ?? null;
    }


    //获取小程序码
    public static function get_wxa_code($access_token, $id, $scene = 'qrcode_id', $path = 'wxa', $is_hyaline = false, $page = 'pages/yd_code/home')
    {
        $client = new Client();

        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;

        $response = $client->post($url, [
            'json' => [
                'page' => $page,
                'scene' => $scene . '=' . $id,
                //'env_version' => 'develop',
                'width' => 280,
                'is_hyaline' => $is_hyaline
            ],
            'headers' => [
                'Content-Type' => 'application/json'
            ]
        ]);

        $body = $response->getBody()->getContents();
        // 如果返回的是图片字节流
        $dir = public_path() . "/qrcode/{$path}/";
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        $filename = $dir . $id . '.png';
        //真实的URL
        $real_url = "/qrcode/{$path}/{$id}.png";
        file_put_contents($filename, $body);

        return $real_url;
    }

    //获取合作店铺商品列表
    public static function get_product_list($page_size = 10)
    {

        //http请求方式：POST
        //https://api.weixin.qq.com/channels/ec/cooperation/product/list?access_token=ACCESS_TOKEN

        //请求参数
        //{
        //    "shop_appid": "wx***************0",
        //    "page_size": 2
        //}
        //请求参数
        $access_token = self::get_access_token();
        $client = new Client();
        $url = 'https://api.weixin.qq.com/channels/ec/cooperation/product/list?access_token=' . $access_token;
        $response = $client->post($url, [
            'json' => [
                'shop_appid' => env('WECHAT_SHOP_APPID'),
                'page_size' => $page_size
            ],
            'headers' => [
                'Content-Type' => 'application/json'
            ],
        ]);
        $data = json_decode($response->getBody(), true);
        return $data;
    }


    //获取合作店铺商品
    public static function get_product($product_id)
    {

        var_dump($product_id);
        //http请求方式：POST
        //https://api.weixin.qq.com/channels/ec/cooperation/product/get?access_token=ACCESS_TOKEN

        //请求参数
        //{
        //    "shop_appid": "wx2b255582a7b4bfd0",
        //    "product_id": 10000157022254
        //}
        //请求参数
        $access_token = self::get_access_token();
        $client = new Client();
        $url = 'https://api.weixin.qq.com/channels/ec/cooperation/product/get?access_token=' . $access_token;
        $response = $client->post($url, [
            'json' => [
                'shop_appid' => env('WECHAT_SHOP_APPID'),
                'product_id' => 10000238745614
            ],
            'headers' => [
                'Content-Type' => 'application/json'
            ],
        ]);
        $data = json_decode($response->getBody(), true);
        return $data;
    }

    /**
     * 发送订阅消息
     */
    public static function send_message(string $openid, string $templateId, string $page, array $data): array
    {
        $access_token = self::get_access_token();
        if (!$access_token) {
            return ['err' => '获取 access_token 失败'];
        }

        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$access_token}";

        $payload = [
            'touser' => $openid,
            'template_id' => $templateId,
            'page' => $page,
            'data' => $data,
            //'miniprogram_state' => 'developer'
        ];
        $client = new Client();
        $response = $client->post($url, [
            'json' => $payload
        ]);

        return json_decode($response->getBody()->getContents(), true);
    }


    //敏感词过滤
    public static function get_sensitive_words($openid, $text)
    {
        $access_token = self::get_access_token();
        if (!$access_token) {
            return ['err' => '获取 access_token 失败'];
        }
        $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token={$access_token}";


        $rawBody = json_encode([
            'openid' => $openid,
            'scene' => 2,
            'version' => 2,
            'content' => $text,
        ], JSON_UNESCAPED_UNICODE);

        $client = new Client();
        $response = $client->post($url, [
            'body' => $rawBody, // 👈 直接发送字符串（raw）  4101021012837
            'headers' => [
                'Content-Type' => 'application/json',
            ],
        ]);
        return json_decode($response->getBody()->getContents(), true);
    }

    //获取小游戏的openid
    public function get_game_openid($js_code)
    {
        $appid = env('WECHAT_GAME_APPID', '');
        $secret = env('WECHAT_GAME_SECRET', '');
        //创建一个有基本URI的客户端
        $client = new Client();
        //发送请求
        $response = $client->request('GET', 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $js_code . '&grant_type=authorization_code');
        //获取返回数据
        $data = json_decode($response->getBody(), true);
        if (isset($data['openid'])) {
            return [$data['openid'], $data['unionid']];
        }
        return [null, null];
    }


}